﻿/**
 * 自动排版
 */
(function(E, $){
var Consts = E.consts,
	reBlock = /^(blockquote|center|div|h[\d]|p)$/i;
	
E.plugin("AutoFormat", {
	icon: {
		width: 60,
		text: '自动排版',
		
		'default': {
			'AutoFormat': {XY:"none" }
		}
	},
	
	click: function(Panel, self, target){
		autoFormat(true);
		E.showNotice('段落首行自动缩进完成');
	}
});

E.plugin("CancelAutoFormat", {
	icon: {
		width: 60,
		text: '自动排版',
		
		'default': {
			'CancelAutoFormat': {XY:"none" }
		}
	},
	
	click: function(Panel, self, target){
		autoFormat(false);
		E.showNotice('取消段落首行自动缩进完成');
	}
});

function autoFormat( isIndent ){
	var dom = E.get('document'), node, childs = E.$("body")[0].childNodes,
		paragraphList = [], paragraph = [];
	
	for (var i = 0, len = childs.length; i < len; i++){
		node = childs[i];
		
		if (1 === node.nodeType){
			// 元素
			if( reBlock.test(node.nodeName) ){
				if( paragraph.length ){
					paragraphList.push( paragraph );
					paragraph = [];
				}
				
				if( /^p$/i.test(node.nodeName) ){
					// 2011-09-10 09:00 潘雪鹏
					// 使用中文空格方式缩进，方便编辑手工控制
					
					if(isIndent){
						$(node).html( $(node).html().replace(/^(\s|&nbsp;|　)*/i, '　　') );
					}else{
						// 去掉段落开头可能存在的空格
						$(node).html( $(node).html().replace(/^(\s|&nbsp;|　)*/i, '') );
					}
				}
			}else{
				// 非段落元素
				paragraph.push(node);
			}
		}else if (3 === node.nodeType){
			// 文本，过滤掉空白
			$.trim(node.nodeValue) && paragraph.push(node);
		}else {
			// 丢弃
		}
	}
	
	if( paragraph.length ){
		paragraphList.push( paragraph );
	}
	
	for (var i = 0, len = paragraphList.length; i < len; i++){
		var p = dom.createElement('p'),
			sublist = paragraphList[i];
		//p.style.textIndent = '2em';
		
		E.$(sublist[0]).before(p);
		
		for (var j = 0, len2 = sublist.length; j < len2; j++){
			E.$(p).append( sublist[j] );
		}
	}
}

})(jQEditor, jQuery);